package com.smooth.common.site.common.aop;

import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;

@Component
@Aspect
public class ReqLogWriter {
	private Logger log = LoggerFactory.getLogger(ReqLogWriter.class);
	@Around(value = "@annotation(org.springframework.web.bind.annotation.RequestMapping)", argNames = "jp")
	public Object logAopWrite(ProceedingJoinPoint jp) throws Throwable {
		long curtime = System.currentTimeMillis();
		Object[] args = jp.getArgs();
		HttpServletRequest request = null;
		try{
			for (Object obj : args) {
				if (obj instanceof HttpServletRequest) {
					request = (HttpServletRequest) obj;
				}
			}
			if(request==null) {
				request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
			}
		}catch(Exception e){
			log.error("",e);
			throw e;
		}
		if (request != null) {
			StringBuffer sbstr = new StringBuffer();
			try{
				Set<String> keyset = request.getParameterMap().keySet();
				for (String key : keyset) {
					String[] values = request.getParameterValues(key);
					for (int i = 0; i < values.length; i++) {
						String value = values[i];
						sbstr.append(key + "=" + value + "&");
					}
				}
				log.info("" + request.getRequestURL().toString() + "?" + sbstr.toString() + "\t" );
				Object object = jp.proceed();// 执行该方法
				String jspstr = JSON.toJSONString(object);
				log.info("" + request.getRequestURL().toString() + "?" + sbstr.toString() + "\t" + jspstr + "\tcost [" + (System.currentTimeMillis() - curtime) + "]");
				return object;
			}catch(Exception e){
				log.error("",e);
				throw e;
			}
		}
		return jp.proceed();
	}
}
